<?php
class Student
{
    private $surname;
    private $first_name;

    private $status;

    private $emails;
    private $grades = [];

    function __construct($surname, $first_name, $status)
    {
        $this->surname = $surname;
        $this->first_name = $first_name;
        $this->status = $status;
        $this->emails = array();
        // $this->grades = array();
    }

    function add_email($which, $address)
    {
        $this->emails[$which] = $address;
    }
    function add_grade($course, $grade)
    {
        $this->grades[] = ['course' => $course, 'grade' => $grade];
    }

    // function average()
    // {
    //     $total = 0;
    //     foreach ($this->grades as $value)
    //         $total += $value;
    //     return $total / count($this->grades);
    // }

    public function average()
    {
        if (empty($this->grades)) {
            return 0;
        }
        $total = 0;
        foreach ($this->grades as $gradeInfo) {
            $total += $gradeInfo['grade'];
        }
        return $total / count($this->grades);
    }

    function toString()
    {
        // $result = $this->first_name . ' ' . $this->surname;
        // $result .= ' (' . $this->average() . ") $this->status\n";

        $result = $this->first_name . ' ' . $this->surname . ' (' . $this->average() . ') ' . $this->status . "\n";
        foreach ($this->emails as $which => $what) {
            $result .= $which . ': ' . $what . "\n";
        }
        $result .= "Courses and Grades:\n";

        // foreach ($this->emails as $which => $what)
        //     $result .= $which . ': ' . $what . "\n";
        // $result .= "\n";
        foreach ($this->grades as $gradeInfo) {
            $course = $gradeInfo['course'];
            $grade = $gradeInfo['grade'];
            $result .= "  Course: " . $course->getCourseName() ." Grade: " . $grade . "\n";
        }
        $result .= "\n";

        return '<pre>' . $result . '</pre>';
    }
}